package com.example.musicplayer.fragment.dialogFragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.musicplayer.MusicStateChangedListener;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.MusicListDialogAdapter;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.objectClass.ListViewLoc;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.settings.MusicPlayerSettings;

public class MusicListDialogFragment extends DialogFragment implements View.OnClickListener
        , MusicStateChangedListener {
    private static final String TAG = "MusicListDialogFragment";
    private static final int UPDATE_BACKGROUND = 1;
    private ListView mListView;
    private View mFooterView;
    private ImageView mImageViewPlayMode;
    private TextView mTextViewModeText;
    private CallBackListener mCallBackListener;
    private MusicService.MusicBinder mMusicBinder;
    private MusicListDialogAdapter mAdapter;
    private final ListViewLoc mListLoc = new ListViewLoc();
    private boolean mSaveListLoc = false;
    private boolean mHasDismiss = false;
    private boolean mShouldDismiss = false;
    private final MyHandler mHandler = new MyHandler();

    @Override
    public void musicCompletion(MusicInfo musicInfo) {
    }

    @Override
    public void musicPrepared(MusicInfo musicInfo) {
    }

    @Override
    public void musicEmpty(MusicInfo musicInfo) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        mShouldDismiss = true;
    }

    @Override
    public void musicFavoriteChanged(MusicInfo musicInfo, boolean result) {
    }

    @Override
    public void musicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
        if (mAdapter != null) {
            mAdapter.musicPlayingStateChanged(isPlaying);
        }
    }

    @Override
    public void musicPlayModeChanged(MusicInfo musicInfo, MusicPlayMode mode) {
    }

    @Override
    public void musicPlayNext(MusicInfo beforeMusic, MusicInfo afterMusic) {
    }

    @Override
    public void musicPlayLast(MusicInfo beforeMusic, MusicInfo afterMusic) {
    }

    @SuppressLint("HandlerLeak")
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == UPDATE_BACKGROUND) {
                Bitmap bitmap = (Bitmap) msg.obj;
                if (getDialog() != null && getDialog().getWindow() != null) {
                    getDialog().getWindow().getDecorView().setBackground(new BitmapDrawable(getResources(), bitmap));
                }
                mAdapter.notifyDataSetChanged();
                //change the image color
                int defaultColor = mAdapter.getDefaultColor();
                mTextViewModeText.setTextColor(defaultColor);
                View view = getView();
                if (view != null) {
                    ((TextView) view.findViewById(R.id.textview_close)).setTextColor(defaultColor);
                    ((ImageView) view.findViewById(R.id.music_list_dialog_mode)).setColorFilter(defaultColor, PorterDuff.Mode.SRC_IN);
                    ((ImageView) view.findViewById(R.id.music_list_dialog_down)).setColorFilter(defaultColor, PorterDuff.Mode.SRC_IN);
                    ((ImageView) view.findViewById(R.id.music_list_dialog_locate)).setColorFilter(defaultColor, PorterDuff.Mode.SRC_IN);
                    ((ImageView) view.findViewById(R.id.music_list_dialog_delete)).setColorFilter(defaultColor, PorterDuff.Mode.SRC_IN);
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music_list_dialog, container, false);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        addListener();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mCallBackListener != null) {
            mMusicBinder = mCallBackListener.getBinder();
        }
        addDialogListener();
        mMusicBinder.addMusicStateChangedListener(this);
        //check if need modify mShouldDismiss
        if (mMusicBinder.getMusicCounts() > 0) {
            mShouldDismiss = false;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mShouldDismiss) {
            dismiss();
        } else {
            //设置对话框的布局
            Window window = null;
            if (getDialog() != null) {
                window = getDialog().getWindow();
            }
            if (window != null) {
                window.getDecorView().setPadding(0, 0, 0, 0);
                window.getDecorView().setBackgroundColor(getResources().getColor(R.color.light_silver));
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = (int) getResources().getDimension(R.dimen.dialog_play_list_width);
                lp.height = (int) getResources().getDimension(R.dimen.dialog_play_list_height);
                lp.gravity = Gravity.BOTTOM;
                window.setAttributes(lp);
            }
            if (window != null && MusicPlayerSettings.isAnimEffect()) {
                window.setWindowAnimations(R.style.MusicListDialogFragment);
            }
            initListView();
            updateView(true);
            if (mSaveListLoc) {
                mListView.setSelectionFromTop(mListLoc.getPosition(), mListLoc.getOffset());
            } else {
                scrollTo();
                mListView.setSelection(mMusicBinder.getNowMusicPosition());
            }
            mHasDismiss = false;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mListView != null && !mShouldDismiss) {
            mListLoc.setLocation(mListView.getFirstVisiblePosition()
                    , mListView.getChildAt(0).getTop());
            if (!mHasDismiss) {
                mSaveListLoc = true;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mMusicBinder != null) {
            mMusicBinder.removeMusicStateChangedListener(this);
        }
    }

    private void initView() {
        if (getView() != null) {
            mListView = getView().findViewById(R.id.listview_music_list_dialog);
            mImageViewPlayMode = getView().findViewById(R.id.music_list_dialog_mode);
            mTextViewModeText = getView().findViewById(R.id.music_list_dialog_text);
        }
    }

    private void addFooterView() {
        if (mFooterView == null) {
            mFooterView = LayoutInflater.from(getContext()).inflate(R.layout.footer_view, mListView, false);
        }
        mListView.removeFooterView(mFooterView);
        mListView.addFooterView(mFooterView, null, false);
    }

    private void addListener() {
        if (getView() != null) {
            getView().findViewById(R.id.music_list_dialog_down).setOnClickListener(this);
            getView().findViewById(R.id.music_list_dialog_locate).setOnClickListener(this);
            getView().findViewById(R.id.music_list_dialog_delete).setOnClickListener(this);
            getView().findViewById(R.id.music_list_dialog_close).setOnClickListener(this);
        }
        mImageViewPlayMode.setOnClickListener(this);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mCallBackListener != null) {
            mCallBackListener.onMusicListDismiss();
        }
        mSaveListLoc = false;
        mHasDismiss = true;
    }

    private void addDialogListener() {
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    if (mCallBackListener != null) {
                        mCallBackListener.onMusicListShow();
                    }
                }
            });
        }
    }

    private void initListView() {
        mAdapter = new MusicListDialogAdapter(mMusicBinder.getMusicList(), getActivity(),
                mMusicBinder.getNowMusicPosition(), this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != mAdapter.getNowMusicPosition()) {
                    mMusicBinder.start(position);
                } else if (!mMusicBinder.isPlaying()) {
                    mMusicBinder.start();
                }
            }
        });
        addFooterView();
    }

    //更新对话框界面
    private void updateView(boolean updateBackground) {
        //记录播放列表歌曲数量
        int counts = 0;
        String modeText = "";
        switch (mMusicBinder.getMode()) {
            case RANDOM:
                mImageViewPlayMode.setImageDrawable(getResources().getDrawable(R.drawable.dialog_music_list_random));
                counts = mMusicBinder.getMusicCounts();
                modeText = "随机播放(" + counts + "首)";
                break;
            case REPEAT:
                mImageViewPlayMode.setImageDrawable(getResources().getDrawable(R.drawable.dialog_music_list_repeat));
                counts = mMusicBinder.getMusicCounts();
                modeText = "顺序播放(" + counts + "首)";
                break;
            case REPEAT_ONE:
                mImageViewPlayMode.setImageDrawable(getResources().getDrawable(R.drawable.dialog_music_list_repeat_one));
                modeText = "单曲循环";
                break;
        }
        mTextViewModeText.setText(modeText);
        mAdapter.setNowMusicPosition(mMusicBinder.getNowMusicPosition());
        if (updateBackground) {
            updateBackground();
        }
    }

    private void updateBackground() {
        new Thread() {
            @Override
            public void run() {
                Message msg = mHandler.obtainMessage(UPDATE_BACKGROUND);
                float ratio = getResources().getDimension(R.dimen.dialog_play_list_width)
                        / getResources().getDimension(R.dimen.dialog_play_list_height);
                Bitmap bitmap = DrawUtil.getStableRatioBitmap(MusicPlayerSettings.isSetMusicPlayListBg() ?
                        MusicPlayerSettings.getMusicPlayListImageBitmap() : mMusicBinder.getAlbumBitmap(), ratio);
                bitmap = DrawUtil.blurBitmap(getContext(), bitmap, 25);
                int color = DrawUtil.getMainColorOfPicture(bitmap, DrawUtil.DARK_VIBRANT);
                mAdapter.setDefaultColor(DrawUtil.getBodyTextColorOfPicture(bitmap, DrawUtil.DARK_VIBRANT));
                //加上一定的透明度
                color = Color.argb(MusicPlayerSettings.getAlphaOfPictureMainColor()
                        , Color.red(color), Color.green(color), Color.blue(color));
                if (bitmap != null) {
                    Canvas canvas = new Canvas(bitmap);
                    canvas.drawColor(color);
                }
                msg.obj = bitmap;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    //滚动到正在播放歌曲的item
    private void scrollTo() {
        Log.d(TAG, "scrollTo(): scroll to current music");
        int position = mMusicBinder.getNowMusicPosition();
        mListView.smoothScrollToPositionFromTop(position, 0, 500);
    }

    public boolean isMusicPlaying() {
        if (mMusicBinder != null) {
            return mMusicBinder.isPlaying();
        }
        return false;
    }

    //删除一首指定位置的歌曲
    public void deleteOneMusic(int index) {
        Log.d(TAG, "deleteOneMusic(): delete one music -> " + index);
        int result = mMusicBinder.deleteOneMusic(index);
        if (result == MusicService.DELETE_STATE_EMPTY) {
            dismiss();
        } else if (result == MusicService.DELETE_CURRENT) {
            updateView(true);
        } else if (result == MusicService.DELETE_ONE) {
            updateView(false);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void updateWhenChangingMusic() {
        Log.d(TAG, "updateWhenChangingMusic(): change current music");
        updateView(true);
        scrollTo();
    }

    public void setCallBackListener(CallBackListener call) {
        Log.d(TAG, "setCallBackListener(): bind the callback listener");
        mCallBackListener = call;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.music_list_dialog_mode:
                doClickMode();
                break;
            case R.id.music_list_dialog_down:
                doClickDown();
                break;
            case R.id.music_list_dialog_locate:
                doClickLocate();
                break;
            case R.id.music_list_dialog_delete:
                doClickDelete();
                break;
            case R.id.music_list_dialog_close:
                doClickClose();
                break;
            default:
                break;
        }
    }

    private void doClickMode() {
        Log.d(TAG, "doClickMode(): try to change the play mode");
        mMusicBinder.changeMode();
        updateView(false);
    }

    private void doClickDown() {
        Log.d(TAG, "doClickDown(): try to scroll to the last of the music list");
        mListView.smoothScrollToPositionFromTop(mMusicBinder.getMusicCounts() - 1, 0);
    }

    private void doClickLocate() {
        Log.d(TAG, "doClickLocate(): try to locate current music");
        mListView.smoothScrollToPositionFromTop(mMusicBinder.getNowMusicPosition(), 0);
    }

    //删除当前列表所有歌曲
    private void doClickDelete() {
        Log.d(TAG, "doClickDelete(): try to clear music list");
        Context context = getContext();
        if (context != null) {
            String title = context.getResources().getString(R.string.prompt);
            String text = context.getResources().getString(R.string.text_clear_music_list);
            NormalAlertDialog normalAlertDialog = new NormalAlertDialog(context, title, text);
            final Dialog dialog = normalAlertDialog.getDialog();
            TextView cancel = normalAlertDialog.getCancel();
            TextView confirm = normalAlertDialog.getConfirm();
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mMusicBinder.deleteAll();
                    mAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                    dismiss();
                }
            });
            Log.d(TAG, "doClickDelete(): start to show alertDialog");
            dialog.show();
        }
    }

    private void doClickClose() {
        Log.d(TAG, "doClickClose(): try to close this music list fragment");
        dismiss();
    }

    public interface CallBackListener {
        //绑定binder对象
        MusicService.MusicBinder getBinder();

        //show dialog
        void onMusicListShow();

        //dismiss dialog
        void onMusicListDismiss();
    }
}